package com.gaohe.service.impl;

import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.gaohe.common.Result;
import com.gaohe.common.ResultMessage;
import com.gaohe.mapper.AdminMapper;
import com.gaohe.pojo.Admin;
import com.gaohe.service.AdminService;
import jakarta.servlet.http.HttpServletRequest;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.util.DigestUtils;
import java.util.Objects;

@Service
public class AdminServiceImpl extends ServiceImpl<AdminMapper, Admin> implements AdminService {
    @Autowired
    private AdminMapper mapper;

    /**
     * 登录
     * @param request 请求对象
     * @param admin 登录用户信息
     * @return
     */
    @Override
    public Result login(HttpServletRequest request, Admin admin) {
       /*

           2.根据用户名和密码查询
           3.查不到 null   返回错误结果
           4.查到了 验证状态
           5.登录成功
        */
        //1.对密码进行加密处理
        admin.setPassword(DigestUtils.md5DigestAsHex(admin.getPassword().getBytes()));
//        //2.根据用户名和密码查询
        LambdaQueryWrapper<Admin> qw = new LambdaQueryWrapper<>();
        qw.eq(Admin::getUsername, admin.getUsername())
                .eq(Admin::getPassword, admin.getPassword());
        Admin selectAdmin = mapper.selectOne(qw);
        //  3.查不到 null   返回错误结果
        if (Objects.isNull(selectAdmin)){
            return Result.error(ResultMessage.USERNAME_OR_PASSWORD_ERROR);
        }
        //4.查到了 验证状态
        if (selectAdmin.getStatus() == 0){
            return Result.error(ResultMessage.ACCOUNT_DISABLED);
        }
        //5.存 session
        request.getSession().setAttribute("loginAdmin",selectAdmin);
        //6.返回结果
        return Result.success(selectAdmin,ResultMessage.LOGIN_SUCCESS);
    }

    /**
     * 退出登录
     * @param request
     * @return
     */
    @Override
    public Result logout(HttpServletRequest request) {
        //删除session 响应结果
        request.getSession().removeAttribute("loginAdmin");
        return Result.success(ResultMessage.LOGOUT_SUCCESS);
    }
}
